<template>
  <AModalPro
    v-bind="$attrs"
    title="编辑字典数据"
    :open="props.open"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="onOk"
    @cancel="handleCancel"
    @close="props.onCancel"
  >
    <ASpin :spinning="spinning">
      <AForm ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <AFormItem label="字典标签" name="dataLabel" :rules="dictRules.dataLabel">
          <AInput v-model:value="formState.dataLabel" placeholder="请输入字典标签" :maxlength="20"></AInput>
        </AFormItem>
        <AFormItem label="字典键值" name="dataValue" :rules="dictRules.dataValue">
          <AInput v-model:value="formState.dataValue" placeholder="请输入字典键值" :maxlength="50"></AInput>
        </AFormItem>
        <AFormItem label="数据状态" name="status">
          <ARadioGroup v-model:value="formState.status" name="radioGroup">
            <ARadio :value="0">正常</ARadio>
            <ARadio :value="1">停用</ARadio>
          </ARadioGroup>
        </AFormItem>
        <AFormItem label="备注" name="remark">
          <ATextarea v-model:value="formState.remark" placeholder="请输入内容" auto-size :maxlength="500"></ATextarea>
        </AFormItem>
      </AForm>
    </ASpin>
  </AModalPro>
</template>

<script setup>
import { ref, toValue, watch } from 'vue';
import { AModalPro } from '@/components/iteration';
import { useState, useFetch } from '@/hooks';
import { dictRules } from '@/constants/rules';
import { fetchGetDictData } from '@/api/system/dictData.js';

defineOptions({
  inheritAttrs: false // 禁用透传
});

const props = defineProps({
  open: { type: Boolean, default: false },
  dataId: [Number, String],
  onFinish: Function,
  onCancel: Function
});

const initValues = {
  dictLabel: '',
  dictValue: '',
  status: 0,
  remark: ''
};
const formRef = ref();
const [formState, setFormState] = useState(initValues);
const [loading, setLoading] = useState(false);
const { spinning, onFetch: onFetchData } = useFetch(fetchGetDictData, false);

watch(
  () => props.open,
  async (open) => {
    if (open) {
      const res = await onFetchData(props.dataId);
      setFormState(res);
    }
  }
);

const handleCancel = () => {
  toValue(formRef).resetFields();
  setFormState(initValues);
  props.onCancel?.();
};

const onOk = async () => {
  try {
    setLoading(true);
    await toValue(formRef)
      .validate()
      .then((res) => props.onFinish?.({ ...res, dataId: props.dataId }));
    toValue(formRef).resetFields();
  } catch (e) {
    await Promise.reject(e);
  } finally {
    setLoading(false);
  }
};
</script>

<style lang="scss" scoped></style>
